package com.rams.jhms.gui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListDataListener;

import com.rams.jhms.Config;
import com.rams.jhms.gui.components.FileSelector;
import com.rams.jhms.gui.datamodels.FSPropsFolderListModel;

import net.miginfocom.layout.CC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

public class FSFolderManagerForm extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7770020581168647792L;

	private static FSPropsFolderListModel listModel = new FSPropsFolderListModel();
	
	private static final JTextField txtPath = new JTextField();
	private static final JButton btnGetPath = new JButton("...");
	private static final JButton btnAddPath = new JButton("Add");
	private static final JList pathsList = new JList(listModel);
	private static final JButton btnClose = new JButton("Close");
	private static final JButton btnRemove = new JButton("Remove");
	private static final JScrollPane scList = new JScrollPane(pathsList);
	
	private static FSFolderManagerForm instance;
	
	public FSFolderManagerForm(ListDataListener listener) {
		super();
		instance = this;
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		listModel.addListDataListener(listener);
		MigLayout ml = new MigLayout(new LC().debug(Config.layoutDebug).noGrid().fill());
		this.setLayout(ml);
		
		Container content = this.getContentPane();
		
		btnClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				instance.dispose();
			}
		});
		
		btnGetPath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				File f = FileSelector.selectFolder(instance, "");
				if (f == null)
					return;
				txtPath.setText(f.getPath());
			}
		});
		
		btnAddPath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (txtPath.getText().equals(""))
					return; // we can't to add empty string
				listModel.addElement(txtPath.getText());
				txtPath.setText("");
			}
		});
		
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				listModel.removeElementAt(pathsList.getSelectedIndex());
			}
		});
		
		content.add(txtPath, new CC().grow());
		content.add(btnGetPath);
		content.add(btnAddPath);
		content.add(scList, new CC().newline().grow());
		content.add(btnRemove, new CC().newline());
		content.add(btnClose);
		
		this.setMinimumSize(new Dimension(330, 270));
		this.setResizable(false);

		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}
}
